package com.syg.servlet02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Properties;

/**
 * 读取*.properties配置文件
 */
@WebServlet("/readprop")
public class _01_ReadProperties extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        readSRC(resp);
        useClassLoader(resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        readSRC(resp);
        useClassLoader(resp);
    }

    /**
     * 读取src下面的*.properties文件(不同目录下,只是文件目录不同)
     * @param response
     */
    private void readSRC(HttpServletResponse response) throws IOException {
        //设置输出的编码格式
        response.setContentType("text/html;charset=utf-8");
        //通过上下文对象读取*.properties文件流
        InputStream in = this.getServletContext().getResourceAsStream("WEB-INF/classes/srcConf.properties");
        //声明操作*.properties文件的对象
        Properties prop =  new Properties();
        //加载文件内容
        prop.load(in);

        //根据键获取值
        String jdbcUrl = prop.getProperty("jdbcUrl");
        String jdbcUsername = prop.getProperty("jdbcUsername");
        String jdbcPassword = prop.getProperty("jdbcPassword");

        //输出信息到页面
        response.getWriter().println("通过ServletContext的方式,srcConf.properties配置文件信息展示如下");
        response.getWriter().println(MessageFormat.format("jdbcUrl={0},jdbcUsername={1},jdbcPassword={2}",jdbcUrl,jdbcUsername,jdbcPassword));
    }

    /**
     * 使用类装载器读取*.properties的配置文件
     * @param response
     */
    private void useClassLoader(HttpServletResponse response) throws IOException {
        //获取当前类的装载器对象
        ClassLoader loader = _01_ReadProperties.class.getClassLoader();
        //通过类装载器对象读取*.properties的配置文件
        InputStream in = loader.getResourceAsStream("properties/srcConf.properties");
        //声明操作*.properties文件的对象
        Properties prop = new Properties();
        //获取文件内容
        prop.load(in);

        //声明输出对象
        PrintWriter out = response.getWriter();
        //获取键和值
        Iterator<String> it = prop.stringPropertyNames().iterator();
        while (it.hasNext()){
            String key = it.next();
            out.println("通过类装载器的方式,srcConf.properties文件中键是："+key+",值是："+prop.getProperty(key));
        }
    }
}
